package com.baitiaojun.common.utils.object;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.common.enums.impl.ServerExpEnums;
import com.baitiaojun.common.exception.ServerException;
import com.baitiaojun.common.utils.exception.ExceptionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ObjectUtils {

    /**
     * 安全的方式获取对象
     * @param val
     * @param defaultValue
     * @return
     * @param <T>
     */
    public static <T> T getValue(T val, T defaultValue) {
        return val != null? val : defaultValue;
    }

    public static boolean isNull(Object object) {
        return object == null;
    }

    /**
     * * 判断一个对象是否非空
     *
     * @param object Object
     * @return true：非空 false：空
     */
    public static boolean isNotNull(Object object) {
        return !isNull(object);
    }

    /**
     * 判断对象是否是数组
     * @param object
     * @return
     */
    public static boolean isArray(Object object) {
        return isNotNull(object) && object.getClass().isArray();
    }

    public static Map<String, Object> toMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        try {
            String jsonString = JSONObject.toJSONString(object);
            if (StringUtils.isNotEmpty(jsonString)) {
                map = new ObjectMapper().readValue(jsonString, new TypeReference<>() {});
            }
        } catch (JsonProcessingException e) {
            log.warn(ExceptionUtils.getExpMsg(e));
            throw new ServerException(ServerExpEnums.EXP_OBJECT_CONVERT);
        }
        return map;
    }
}
